import { defineStore } from 'pinia';
import { router } from '@/router';
import { encryptedRsa } from '@/utils/crypto/encrypt-rsa';
import { decryptedDes } from '@/utils/crypto/encrypt-des';
import { getPublicKey } from '@/utils/publicKey';
import request from '@/utils/request';
import { tokenName } from '@/config/index';
import { setAccessToken } from '@/utils/accessToken';
import { useSnackbar } from '@/composables/useSnackbar';
import { useMenuStore } from './menu';
import { nextTick } from 'vue';
import { getStorage, setStorage, removeStorage } from '@/utils/storage';
import { getFingerprint } from '@/utils/fingerprint';
import { getDeviceInfo } from '@/utils/device';

const encryptRSA = true; // 是否启用RSA加密

interface LoginData {
    principal: string;
    password: string;
    verificationCode?: string;
    uuid?: string;
    loginFrom: string;
    fingerprint: string;
    deviceInfo: string;
}




interface EncryptedData {
    encryptData: string;
}

export const useAuthStore = defineStore({
    id: 'auth',
    state: () => {
        console.log('=== Auth Store 初始化 ===');
        const accessToken = localStorage.getItem(tokenName) || '';
        const username = getStorage('opsli-username') || '';
        const avatar = getStorage('opsli-avatar') || '';
        const permissions = getStorage('opsli-permissions') || [];
        const perms = getStorage('opsli-perms') || [];
        const userInfo = getStorage('opsli-userInfo') || {};

        // console.log('从缓存读取的数据:');
        // console.log('- accessToken:', accessToken ? '存在' : '不存在');
        // console.log('- username:', username);
        // console.log('- avatar:', avatar);
        // console.log('- userInfo:', userInfo);

        return {
            // initialize state from local storage to enable user to stay logged in
            user: null as any,
            accessToken,
            username,
            avatar,
            permissions,
            perms,
            returnUrl: null,
            userInfo,
        };
    },
    actions: {
        async login(email: string, password: string, captcha?: string, uuid?: string) {
            try {
                let loginData: LoginData | EncryptedData = {
                    principal: email,
                    password: password,
                    loginFrom: "0",
                    fingerprint: await getFingerprint(), // 指纹
                    deviceInfo: await getDeviceInfo(), // 设备信息
                };

                if (captcha && uuid) {
                    loginData = {
                        ...loginData,
                        verificationCode: captcha,
                        uuid: uuid
                    };
                }
                if (captcha) {
                    loginData = {
                        ...loginData,
                        verificationCode: captcha,
                    };
                }

                // console.log(loginData);


                if (encryptRSA) {
                    const publicKey = getPublicKey() || '';
                    const encrypted = encryptedRsa(loginData, publicKey);
                    loginData = {
                        encryptData: encrypted,
                    };
                }

                const response = await request({
                    url: '/system/login',
                    method: 'post',
                    data: loginData
                });

                let tmpData;
                if (encryptRSA && response.data) {
                    const publicKey = getPublicKey() || '';
                    const decryptedStr = decryptedDes(response.data, publicKey);
                    tmpData = JSON.parse(decryptedStr);
                } else {
                    tmpData = response.data;
                }

                const accessToken = tmpData?.["accessToken"];
                // console.log(1);

                if (!accessToken) {
                    const { showSnackbar } = useSnackbar();
                    showSnackbar({
                        text: `登录接口异常，未正确返回${tokenName}...`,
                        color: 'error'
                    });
                    return false;
                }
                // console.log(2);

                this.accessToken = accessToken;
                setAccessToken(accessToken);

                // 获取用户信息
                await this.getUserInfo();
                // console.log(3);
                // 显示欢迎消息
                const hour = new Date().getHours();
                const thisTime =
                    hour < 8
                        ? "早上好"
                        : hour <= 11
                            ? "上午好"
                            : hour <= 13
                                ? "中午好"
                                : hour < 18
                                    ? "下午好"
                                    : "晚上好";

                const { showSnackbar } = useSnackbar();
                // console.log(4);
                showSnackbar({
                    text: `欢迎登录！${thisTime}！`,
                    color: 'success'
                });
                // console.log(5);
                // 使用 replace 模式进行路由跳转，避免在历史记录中留下登录页
                const redirect = this.returnUrl || '/main';
                //看看当前有哪里路由
                // console.log(router.currentRoute.value.matched);

                // 2. 获取菜单并注册动态路由
                const menuStore = useMenuStore();
                await menuStore.getRouterList();
                // 等待路由表刷新
                await nextTick();

                // 登录成功后加载用户列表
                const { useUserStore } = await import('@/store/user');
                const userStore = useUserStore();
                await userStore.loadAllUsers();

                // 跳转到主页
                // console.log(router.currentRoute.value.matched);

                await router.push('/index');
                // console.log(6);
                return true;
            } catch (error) {
                throw new Error(error as string);
                const { showSnackbar } = useSnackbar();
                showSnackbar({
                    text: '登录失败，请重试',
                    color: 'error'
                });
                return error;
            }
        },

        async getUserInfo() {
            try {
                // console.log('开始获取用户信息...');
                const { data } = await request({
                    url: '/api/v1/system/user/getInfo',
                    method: 'get',
                    headers: {
                        [tokenName]: this.accessToken
                    }
                });

                if (!data) {
                    const { showSnackbar } = useSnackbar();
                    showSnackbar({
                        text: '验证失败，请重新登录...',
                        color: 'error'
                    });
                    return false;
                }

                // console.log('用户信息数据:', data);
                const { roles, perms, realName, avatar } = data;
                if (roles && realName && Array.isArray(roles)) {
                    this.permissions = roles;
                    this.perms = perms;
                    this.username = realName;
                    this.avatar = avatar || '';
                    this.userInfo = data;


                    // 持久化用户数据
                    setStorage('opsli-username', realName);
                    console.log("存储头像", avatar);

                    setStorage('opsli-avatar', avatar || '');
                    setStorage('opsli-permissions', roles);
                    setStorage('opsli-perms', perms);
                    setStorage('opsli-userInfo', data);

                    // console.log('用户数据已保存到缓存');


                    return this.permissions;
                } else {
                    // console.error('用户信息格式异常:', { roles, realName, data });
                    const { showSnackbar } = useSnackbar();
                    showSnackbar({
                        text: '用户信息接口异常',
                        color: 'error'
                    });
                    return data;
                }
            } catch (error) {
                // console.error('获取用户信息失败', error);
                return false;
            }
        },

        logout() {
            const menuStore = useMenuStore();
            menuStore.resetRoutes();

            this.accessToken = '';
            this.user = null;
            this.username = '';
            this.avatar = '';
            this.permissions = [];
            this.perms = [];
            this.userInfo = {};

            // 清除持久化数据
            localStorage.removeItem(tokenName);
            removeStorage('opsli-username');
            removeStorage('opsli-avatar');
            removeStorage('opsli-permissions');
            removeStorage('opsli-perms');
            removeStorage('opsli-userInfo');

            router.push('/auth/login');
            window.location.reload();
        }
    }
});
